package com.cast.health.controller;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.cast.health.entity.Result;
import com.cast.health.pojo.Member;
import com.cast.health.service.MemberService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

@Controller
@RequestMapping("/login.do")
public class LoginController {

    @Autowired
    private MemberService memberService;

    @Autowired
    private HttpServletRequest request;


    public Result login(@RequestBody Member member) {
        //检查参数
        if (member == null) {
            return new Result(false, "参数异常!");
        }
        //得到用户名和密码
        String name = member.getName();
        String password = member.getPassword();
        //密码加密
        String ps = DigestUtils.md5DigestAsHex(password.getBytes());
        //判断用户名是否存在
        LambdaQueryWrapper<Member> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Member::getName, name);
        //调用service查询对应的用户信息是否存在
        Member one = memberService.getOne(wrapper);
        //判断
        if (one == null) {
            return new Result(false, "该用户名不存在!");
        }
        //存在的时候,判断密码
        if (!one.getPassword().equals(password)) {
            return new Result(false, "密码错误!");
        }
        //6.获取session,把用户id存入session当中
        HttpSession session = request.getSession();
        session.setAttribute("id", one.getId());
        return new Result(true, "static/pages/main.html:184", one);
    }
}
